"""
认证相关路由模块

该模块提供用户认证功能，包括用户登录和令牌刷新。
使用JWT令牌进行身份验证，确保系统安全。
"""

from fastapi import APIRouter, HTTPException, status, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.schemas.user import LoginRequest, TokenData, UserSchema, LoginResponse
from app.schemas.response import ApiResponse
from app.services.auth_service import AuthService
from app.core.security import create_access_token, verify_token
from app.core.deps import get_db
from datetime import timedelta
from app.core.config import settings
from app.core.exceptions import AuthenticationException
import logging

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post("/login", response_model=ApiResponse)
async def login(user_credentials: LoginRequest, db: Session = Depends(get_db)):
    """用户登录端点"""
    logger.info(f"用户登录: username='{user_credentials.username}' password='{user_credentials.password}'")
    
    # 创建认证服务实例
    auth_service = AuthService(db)
    
    # 验证用户凭据
    token_data = auth_service.login(user_credentials)
    
    # 转换用户信息（移除敏感字段）
    user_info = token_data['user']
    
    logger.info(f"用户登录成功: {user_info['username']} (ID: {user_info['id']})")
    
    # 返回令牌信息
    return ApiResponse(
        success=True,
        data={
            "token": token_data["token"],
            "user": user_info,
            "expiresIn": token_data["expiresIn"]
        },
        message="登录成功"
    )

@router.post("/logout", response_model=ApiResponse)
async def logout(token_data: TokenData = Depends(verify_token), db: Session = Depends(get_db)):
    """用户登出"""
    logger.info(f"用户登出: {token_data.username}")
    return ApiResponse(
        success=True,
        message="登出成功"
    )

@router.get("/userinfo", response_model=ApiResponse)
async def get_user_info(token_data: TokenData = Depends(verify_token), db: Session = Depends(get_db)):
    """获取用户信息"""
    logger.info(f"获取用户信息: {token_data.username}")
    auth_service = AuthService(db)
    user_info = auth_service.get_user_info(token_data.username)
    return ApiResponse(
        success=True,
        data=user_info
    )

@router.post("/refresh", response_model=ApiResponse)
async def refresh_token(token_data: TokenData = Depends(verify_token), db: Session = Depends(get_db)):
    """刷新访问令牌端点"""
    logger.info(f"用户刷新令牌: {token_data.username} (ID: {token_data.user_id})")
    
    # 创建新的访问令牌
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={
            "user_id": token_data.user_id,
            "username": token_data.username
        },
        expires_delta=access_token_expires
    )
    
    logger.info(f"令牌刷新成功: {token_data.username} (ID: {token_data.user_id})")
    
    # 返回新的令牌信息
    return ApiResponse(
        success=True,
        data={
            "token": access_token,
            "token_type": "bearer"
        },
        message="令牌刷新成功"
    )